import UIKit

open class Label: UILabel {
    
    public typealias Action = (Label) -> Swift.Void
    
    fileprivate var actionOnTouch: Action?
    
    open var insets: UIEdgeInsets = .zero
    
    convenience init(frame: CGRect, font :UIFont?, text: String?, textColor: UIColor?, numOfLines: Int, textAligment: NSTextAlignment) {

        self.init(frame:frame)
        
        self.text = text
        self.font = font
        self.textColor = textColor
        self.numberOfLines = numOfLines
        self.textAlignment = textAligment
        self.lineBreakMode = .byTruncatingTail
        self.setContentCompressionResistancePriority(.fittingSizeLevel, for: .horizontal)

    }
    
    convenience init(font : UIFont, textColor : UIColor) {
        self.init()
        self.font = font
        self.textColor = textColor
    }
    
    convenience init(font : UIFont, textColor : UIColor, defaultText: String) {
        self.init()
        self.font = font
        self.textColor = textColor
        self.text = defaultText
    }
    
    override open func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: insets))
    }
    
    // Override -intrinsicContentSize: for Auto layout code
    override open var intrinsicContentSize: CGSize {
        var contentSize = super.intrinsicContentSize
        contentSize.height += insets.top + insets.bottom
        contentSize.width += insets.left + insets.right
        return contentSize
    }
    
    // Override -sizeThatFits: for Springs & Struts code
    override open func sizeThatFits(_ size: CGSize) -> CGSize {
        var contentSize = super.sizeThatFits(size)
        contentSize.height += insets.top + insets.bottom
        contentSize.width += insets.left + insets.right
        return contentSize
    }
    
    public func action(_ closure: @escaping Action) {
        Log("action did set")
        if actionOnTouch == nil {
            let gesture = UITapGestureRecognizer(
                target: self,
                action: #selector(Label.actionOnTouchUpInside))
            gesture.numberOfTapsRequired = 1
            gesture.numberOfTouchesRequired = 1
            self.addGestureRecognizer(gesture)
            self.isUserInteractionEnabled = true
        }
        self.actionOnTouch = closure
    }
    
    @objc internal func actionOnTouchUpInside() {
        actionOnTouch?(self)
    }
}

class CopyLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setEvent()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        addLongPressGesture()
    }
    
    // MARK: - 必须实现的两个方法
    // 重写返回
    override var canBecomeFirstResponder: Bool {
        return true
    }
    // 可以响应的方法
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(copyText) {
            return true
        }
        return false
    }
    
    private func setEvent(){
        addLongPressGesture()
        NotificationCenter.default.addObserver(forName: UIMenuController.willHideMenuNotification, object: nil, queue: nil) { (note) in
            self.backgroundColor = UIColor.white
        }
    }
    
    // UILabel默认是不接收事件的，添加touch事件
    private func addLongPressGesture(){
        self.isUserInteractionEnabled = true
        let longTap = UILongPressGestureRecognizer.init(target: self, action: #selector(longTapRecognizer))
        // 长按手势最小触发时间
        longTap.minimumPressDuration = 1.0
        // 长按手势需要的同时敲击触碰数（手指数）
        longTap.numberOfTouchesRequired = 1
        // 长按有效移动范围（从点击开始，长按移动的允许范围 单位 px
        //        longTap.allowableMovement = 15
        self.addGestureRecognizer(longTap)
    }
    
    @objc func longTapRecognizer(recognizer:UIGestureRecognizer){
        if recognizer.state == .ended{
            print("ended")
            self.backgroundColor = UIColor.white
            return
        }else if recognizer.state == .began{
            print("began")
            self.backgroundColor = UIColor.lightGray
            setMenuItems()
        }
    }
    private func setMenuItems(){
        self.becomeFirstResponder()
        // 如果 Menu 已经被创建那就不再重复创建 menu
        if (UIMenuController.shared.isMenuVisible){
            return
        }
        let item1 = UIMenuItem.init(title: "复制", action: #selector(copyText))
        // 单例的形式获取menu
        let menu = UIMenuController.shared
        // 设置箭头方向
        menu.arrowDirection = .default
        // 设置 Menu 所显示的 items
        menu.menuItems = [item1]
        // 设置添加上 menu 的目标控件的 rect 和目标控件
        menu.setTargetRect(self.frame, in: self.superview!)
        // 令 Menu 可见
        menu.setMenuVisible(true, animated: true)
    }
    
    // MARK: 点击复制响应的方法
    // 内容复制到粘贴板
    @objc private func copyText(){
        let pboard = UIPasteboard.general
        pboard.string = self.text
        print(self.text ?? "")
    }
}
